<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="服务名称" prop="serviceName">
        <el-input
          v-model="queryParams.serviceName"
          placeholder="请输入服务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:park_service:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:park_service:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:park_service:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:park_service:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="park_serviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="serviceId" />
      <el-table-column label="服务名称" align="center" prop="serviceName" />
      <el-table-column label="服务图片" align="center" prop="serviceImage" width="100">
        <template slot-scope="scope">
          <el-image 
            v-if="scope.row.serviceImage"
            :src="getFullImageUrl(scope.row.serviceImage)" 
            style="width: 50px; height: 50px;"
            :preview-src-list="[getFullImageUrl(scope.row.serviceImage)]">
          </el-image>
          <span v-else>暂无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:park_service:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:park_service:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改园区仓库服务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="form.serviceName" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="服务图片" prop="serviceImage">
          <EditImage
            v-model="form.serviceImage"
            :cropper-config="{
              autoCrop: true,
              autoCropWidth: 64,
              autoCropHeight: 64,
              fixedBox: false,
              outputType: 'png'
            }"
            :dialog-width="'800px'"
            :cropper-height="400"
            upload-tip="支持 JPG、PNG 格式，建议尺寸 64x64，文件大小不超过 5MB"
            placeholder-text="请上传服务图片，建议尺寸 64x64 像素"
            cropper-title="园区服务图片裁剪"
            :max-file-size="5"
            @image-cropped="onImageCropped"
            @image-removed="onImageRemoved"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPark_service, getPark_service, delPark_service, addPark_service, updatePark_service, uploadPark_serviceFile } from "@/api/system/park_service"
import EditImage from '@/components/EditImage/EditImage.vue'
import { VueCropper } from "vue-cropper"
import { debounce } from '@/utils'
import { BASE_FILE_URL, BASE_API } from '@/utils/constants'

export default {
  name: "Park_service",
  components: { EditImage },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 园区仓库服务表格数据
      park_serviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceName: null,
        serviceImage: null,
        crateTimer: null,
        updateTimer: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 图片裁剪相关
      croppedImageBlob: null
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 拼接服务器图片地址 */
    getFullImageUrl(imageUrl) {
      if (!imageUrl) return '';
      // 如果已经是http/https/base64开头，直接返回
      if (/^(http|https):\/\//.test(imageUrl) || imageUrl.startsWith('data:image/')) {
        return imageUrl;
      }
      // 兼容斜杠
      if (imageUrl.startsWith('/')) {
        return BASE_API + imageUrl;
      }
      // 默认拼接文件服务器路径
      return BASE_FILE_URL + imageUrl;
    },
    /** 查询园区仓库服务列表 */
    getList() {
      this.loading = true
      listPark_service(this.queryParams).then(response => {
        this.park_serviceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        serviceId: null,
        serviceName: null,
        serviceImage: null,
        crateTimer: null,
        updateTimer: null
      }
      this.croppedImageBlob = null // 新增：重置裁剪图片
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.serviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加园区仓库服务"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const serviceId = row.serviceId || this.ids
      getPark_service(serviceId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改园区仓库服务"
      })
    },
    /** 提交按钮 */
    async submitForm() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          // 处理图片上传（新增或修改时）
          if (this.croppedImageBlob) {
            // 有裁剪后的图片blob，先上传图片
            try {
              const formData = new FormData()
              formData.append('file', this.croppedImageBlob, 'park_service.png')
              formData.append('type', 2) // 新增：上传时带上type=2参数
              const res = await uploadPark_serviceFile(formData)
              console.log('res', res)
              if (res && res.code === 200 && res.fileName) {
                this.form.serviceImage = res.fileName || res.url // 兼容返回格式
              } else {
                this.$modal.msgError("图片上传失败1")
                return
              }
            } catch (e) {
              console.log(e)
              this.$modal.msgError("图片上传失败2")
              return
            }
          }
          if (this.form.serviceId != null) {
            updatePark_service(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPark_service(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const serviceIds = row.serviceId || this.ids
      this.$modal.confirm('是否确认删除园区仓库服务编号为"' + serviceIds + '"的数据项？').then(function() {
        return delPark_service(serviceIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/park_service/export', {
        ...this.queryParams
      }, `park_service_${new Date().getTime()}.xlsx`)
    },
    // EditImage组件回调方法
    onImageCropped(blob, base64Url) {
      this.croppedImageBlob = blob
      console.log('图片裁剪完成:', blob, base64Url)
    },
    onImageRemoved() {
      this.croppedImageBlob = null
      console.log('图片已删除')
    }
  }
}
</script>

<style scoped lang="scss">
</style>
